// pages/index/add_event/add_event.js
const db = wx.cloud.database()
const cloudEvenList = db.collection("eventList")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    color: 'cyan',
    tabCur: 0,
    name: null,
    tabList: ["正/倒数日", "生日", "纪念日"],
    date: '2020-01-01',
    remark: null,
    event: {},
    namePlaceholder: null,
    datePlaceholder: null,
    remarkPlaceholder: null
  },

  tabSelect(e) {
    this.setData({
      tabCur: e.currentTarget.dataset.id,
    })
  },

  nameChange(e) {
    this.setData({
      name: e.detail.value
    })
  },

  dateChange(e) {
    this.setData({
      date: e.detail.value
    })

    console.log(this.data.date)
  },

  textareaInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  submitEvent() {
    if (this.data.name === null) {
      wx.showModal({
        title: '失败',
        content: '请填写事件名',
      })
      return;
    }

    // 调用云函数
    const that = this
    wx.cloud.callFunction({
      name: 'update',
      data: {
        _id: this.data.event._id,
        name: this.data.name,
        date: this.data.date,
        remark: this.data.remark
      },
      success: res => {
        console.log('update调用成功: ', res)
      },
      fail: err => {
        console.error('add调用失败', err)
      }
    })

    let eventList = wx.getStorageSync('eventList')
    let i = 0
    for (i = 0; i < eventList.length; i++) {
      if (eventList[i]._id === that.data.event._id) {
        break;
      }
    }

    console.log(i)

    if (i < eventList.length) {
      eventList.splice(i, 1);

      let eventUpdated = {
        '_id': this.data.event._id,
        '_openid': this.data.event._openid,
        'name': this.data.name,
        'date': this.data.date,
        'createDate': this.data.event.createDate,
        'remark': this.data.remark
      }
      //let eventList = wx.getStorageSync('eventList')
      eventList.splice(i, 0, eventUpdated)
      wx.setStorageSync('eventList', eventList)

      wx.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 2000
      })
      wx.navigateBack({
      })
    } else {
      wx.showToast({
        title: '修改失败',
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      color: wx.getStorageSync('color')
    })
    const event = JSON.parse(options.event_json)
    this.setData({
      event: event,
      namePlaceholder: event.name,
      datePlaceholder: event.date,
      remarkPlaceholder: event.remark
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})